#!/usr/bin/env ruby
# unixbench.workload is defined as the total operations in unixbench for
# all processes/threads

LKP_SRC = ENV['LKP_SRC'] || File.dirname(File.dirname(File.dirname(File.realpath($PROGRAM_NAME))))

require "#{LKP_SRC}/lib/log"
require "#{LKP_SRC}/lib/string"
require 'time'

while (line = $stdin.gets)
  line = line.chomp.resolve_invalid_bytes

  case line
  when /^Benchmark Run: .+ (\d+:\d+:\d+) - (\d+:\d+:\d+)$/
    # Benchmark Run: Tue Jan 01 2019 15:48:24 - 15:56:36
    # We only care about the difference value between end time and start time
    start_time = Time.parse($1).to_f
    end_time = Time.parse($2).to_f
    duration = if end_time > start_time
                 end_time - start_time
               else
                 end_time + 3600 * 24 - start_time # date overflow
               end
  when /^.+ Benchmarks .*Index .* INDEX$/
    # System Benchmarks Partial Index              BASELINE       RESULT    INDEX
    # 2D Graphics Benchmarks Partial Index         BASELINE       RESULT    INDEX
    # 3D Graphics Benchmarks Index Values          BASELINE       RESULT    INDEX
    # Non-Index Benchmarks Partial Index           BASELINE       RESULT    INDEX
    line = $stdin.gets
    line = line.chomp.resolve_invalid_bytes

    throughput = line.split[-2].to_f unless line.empty?
  when /^.+? ([\d.]+) (KBps|lps|lpm|score)\s+\([\d.]+ s, \d+ samples?\)/
    # File Write 1024 bufsize 2000 maxblocks      3121976.0 KBps  (30.0 s, 7 samples)
    # File Read 1024 bufsize 2000 maxblocks     438625975.6 KBps  (30.0 s, 7 samples)
    # Recursion Test -- Tower of Hanoi           16724188.3 lps   (20.0 s, 7 samples)
    # 2D graphics: circles                           6479.5 score (50.0 s, 7 samples)
    throughput = $1.to_f
  when /^.+ Benchmarks Index Score .* ([0-9.]+)$/
    score = $1.to_f
  end
end

if duration.nil? || throughput.nil?
  log_error 'miss duration or throughput'
  exit
end

workload = duration * throughput
puts "score: #{score}" if score
puts "throughput: #{throughput}"
puts "workload: #{workload}"
